{% extends "pc/template.html" %}

{% block title %}
BlackWidow Translation
{% endblock %}

{% include 'pc/公共样式配置/CSS总样式.html' %}

{% block css %}
<!-- Custom CSS for translation page -->
<style>
    body {
        background: #f7f8fa;
    }

    .bw-header {
        background: #fff;
        border-bottom: 1px solid #f0f0f0;
        padding: 18px 0 12px 0;
        margin-bottom: 32px;
    }

    .bw-logo {
        font-family: 'Pacifico', cursive;
        font-size: 2rem;
        color: #377dff;
        margin-left: 24px;
    }

    .bw-lang-select,
    .bw-switch-btn {
        min-width: 90px;
        border-radius: 8px;
        background: #f7f8fa;
        border: none;
        margin: 0 8px;
        font-weight: 500;
    }

    .bw-switch-btn {
        width: 40px;
        height: 40px;
        background: #fff;
        border: 1px solid #e0e0e0;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.2rem;
        margin: 0 8px;
    }

    .bw-header-actions {
        margin-right: 36px;
    }

    .bw-header-actions .btn {
        margin-left: 16px;
        border-radius: 12px;
        font-weight: 500;
        font-size: 1.08rem;
        box-shadow: none;
        transition: all 0.18s;
        padding: 7px 22px;
    }

    .bw-header-actions .btn-pro {
        background: #f7f8fa;
        color: #377dff;
        border: 1.5px solid #e0e0e0;
        box-shadow: 0 2px 8px 0 rgba(55, 125, 255, 0.04);
    }

    .bw-header-actions .btn-pro:hover {
        background: #e0eaff;
        color: #255ecb;
        border-color: #b3d4fc;
    }

    .bw-header-actions .btn-free {
        background: linear-gradient(90deg, #377dff 0%, #67e8f9 100%);
        color: #fff;
        border: none;
        box-shadow: 0 4px 16px 0 rgba(55, 125, 255, 0.13);
        font-weight: 600;
        letter-spacing: 1px;
    }

    .bw-header-actions .btn-free:hover {
        background: linear-gradient(90deg, #255ecb 0%, #67e8f9 100%);
        color: #fff;
        transform: translateY(-2px) scale(1.04);
        box-shadow: 0 8px 24px 0 rgba(55, 125, 255, 0.18);
    }

    @media (max-width: 600px) {
        .bw-header-actions {
            margin-right: 8px;
        }

        .bw-header-actions .btn {
            padding: 6px 12px;
            font-size: 0.98rem;
            margin-left: 8px;
        }
    }

    .bw-translate-main {
        display: flex;
        justify-content: center;
        align-items: flex-start;
        gap: 32px;
        margin-top: 32px;
    }

    .bw-card {
        background: #fff;
        border-radius: 18px;
        box-shadow: 0 2px 16px 0 rgba(55, 125, 255, 0.04);
        padding: 24px 24px 16px 24px;
        width: 500px;
        min-height: 260px;
        display: flex;
        flex-direction: column;
        position: relative;
    }

    .bw-card-header {
        display: flex;
        align-items: center;
        gap: 18px;
        margin-bottom: 12px;
        color: #b0b3bb;
        font-size: 1.2rem;
    }

    .bw-card-header .bx {
        cursor: pointer;
        transition: color 0.2s;
    }

    .bw-card-header .bx:hover {
        color: #377dff;
    }

    .bw-input-area {
        flex: 1;
        border: none;
        outline: none;
        font-size: 1.1rem;
        color: #333;
        background: transparent;
        resize: none;
        min-height: 90px;
        margin-bottom: 8px;
    }

    .bw-placeholder {
        color: #b0b3bb;
    }

    .bw-translated-text {
        color: #333;
        max-height: 400px;
        overflow-y: auto;
        white-space: pre-wrap;
        word-wrap: break-word;
        padding-right: 8px;
    }

    .bw-translated-text::-webkit-scrollbar {
        width: 6px;
    }

    .bw-translated-text::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
    }

    .bw-translated-text::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3px;
    }

    .bw-translated-text::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
    }

    .bw-card-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 8px;
    }

    .bw-char-count {
        color: #b0b3bb;
        font-size: 0.95rem;
    }

    .bw-translate-btn {
        background: #377dff;
        color: #fff;
        border: none;
        border-radius: 8px;
        padding: 6px 28px;
        font-size: 1.1rem;
        font-weight: 500;
        transition: background 0.2s;
    }

    .bw-translate-btn:hover {
        background: #255ecb;
    }

    @media (max-width: 1100px) {
        .bw-translate-main {
            flex-direction: column;
            align-items: center;
        }

        .bw-card {
            width: 95vw;
            max-width: 600px;
        }
    }

    .bw-banner {
        background: linear-gradient(90deg, #377dff 0%, #67e8f9 100%);
        color: #fff;
        font-size: 1.08rem;
        padding: 10px 0;
        letter-spacing: 1px;
        font-weight: 500;
        margin-bottom: 0;
    }
</style>
{% endblock %}

{% block content %}
<div class="bw-header d-flex align-items-center justify-content-between">
    <div class="d-flex align-items-center">
        <span class="bw-logo">logo</span>
    </div>
    <div class="d-flex align-items-center" style="min-width: 300px;">
        <div class="bw-lang-info" style="color: #666; font-size: 0.95rem; white-space: nowrap; margin-right: 16px;">
            <span id="detectedLang">自动检测语言</span>
        </div>
        <div style="display: flex; align-items: center; white-space: nowrap;">
            <span style="color: #666; margin-right: 8px;">翻译成</span>
            <!-- 自定义语言选择面板 -->
            <div id="targetLangPanelTrigger" class="custom-lang-trigger" style="min-width:120px;display:inline-block;cursor:pointer;border:1px solid #e0e0e0;border-radius:8px;padding:6px 16px;background:#fff;">
                <span id="targetLangSelectedText">请选择语言</span>
                <i class="bx bx-chevron-down"></i>
            </div>
            <div id="targetLangPanel" class="custom-lang-panel" style="display:none;position:absolute;z-index:9999;top:60px;left:50%;transform:translateX(-50%);background:#fff;border-radius:12px;box-shadow:0 4px 24px rgba(0,0,0,0.08);padding:24px 40px 24px 32px;max-width:800px;max-height:420px;overflow-y:auto;overflow-x:hidden;">
                <div style="margin-bottom: 16px;">
                    <input type="text" id="langSearchInput" placeholder="搜索语言（支持拼音首字母）" style="width:100%;padding:8px 12px;border:1px solid #e0e0e0;border-radius:8px;font-size:0.95rem;outline:none;transition:border-color 0.2s;" />
                </div>
                <div id="targetLangGrid" style="display:grid;grid-template-columns:repeat(5,1fr);gap:18px 32px;"></div>
            </div>
            <input type="hidden" id="targetLang" value="">
        </div>
    </div>
    <div class="bw-header-actions d-flex align-items-center">
        <div class="group-badge me-3">
            <span style="background: linear-gradient(90deg, #377dff 0%, #67e8f9 100%); color: white; padding: 4px 12px; border-radius: 20px; font-size: 0.9rem; font-weight: 500;">
                <i class='bx bx-group' style="margin-right: 4px;"></i>交流群
            </span>
        </div>
    </div>
</div>
<!-- 公告横幅区 -->
<!-- <div class="bw-banner text-center" id="bwBanner">
    🎉 当前为开源版本，点击右上角"升级 Pro"获取完整功能！
</div> -->

<div class="bw-translate-main">
    <!-- Left Card: Input -->
    <div class="bw-card">
        <div class="bw-card-header">
            <i class='bx bx-upload'></i>
            <i class='bx bx-image'></i>
        </div>
        <textarea class="bw-input-area" id="sourceText" maxlength="5000" placeholder="请输入或粘贴文本，或拖拽文件到此处"></textarea>
        <div class="bw-card-footer">
            <span class="bw-char-count"><span id="charCount">0</span>/5000</span>
            <button class="bw-translate-btn" id="translateBtn">翻译</button>
        </div>
    </div>
    <!-- Right Card: Output -->
    <div class="bw-card">
        <div class="bw-card-header">
            <i class='bx bx-copy'></i>
        </div>
        <div class="bw-input-area bw-placeholder" id="translatedText"
            style="max-height: 400px; overflow-y: auto; white-space: pre-wrap; word-wrap: break-word; padding-right: 8px; user-select: text;">
            翻译结果将显示在这里</div>
    </div>
</div>

<!-- 交流群弹窗 -->
<div class="modal fade show" id="groupModal" tabindex="-1" style="display:none; background:rgba(0,0,0,0.35);"
    aria-modal="true" role="dialog">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content" style="border-radius:18px;">
            <div class="modal-header border-0" style="padding-bottom:0;">
                <h5 class="modal-title" style="font-weight:700; color:#377dff;">
                    <i class='bx bx-group' style="margin-right: 8px;"></i>
                    加入交流群
                </h5>
                <button type="button" class="btn-close" id="closeGroupModal" aria-label="Close"></button>
            </div>
            <div class="modal-body" style="padding: 24px 32px; text-align:center;">
                <div style="font-size:1.2rem; color:#377dff; font-weight:600; margin-bottom:16px;">
                    欢迎加入我们的技术交流群！
                </div>
                <div style="font-size:1rem; color:#666; margin-bottom: 24px;">
                    一起探讨、分享、进步！
                </div>
                <div style="display: flex; align-items: center; justify-content: center; gap: 32px; margin-bottom: 0;">
                    <img src="/media/管理员微信.jpg" alt="微信二维码"
                        style="max-width: 300px; max-height: 300px; width: 100%; height: auto; border-radius:12px; box-shadow:0 4px 12px rgba(55,125,255,0.1); display: block;">
                    <div style="text-align:left; min-width: 140px;">
                        <div style="font-size:1.1rem; margin-bottom:12px;">添加群主微信</div>
                        <div style="font-weight:600; color:#255ecb; margin-bottom:12px;">duyanbz</div>
                        <div style="font-size:0.9rem; color:#666;">扫码添加微信，备注：翻译项目</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script src="/static/HubUI/js/l.js"></script>
<script>
    const languageList = Object.entries(getLanguageList()).map(([langCode, langData]) => ({
        code: langCode,
        zhName: langData.zhName,
        enName: langData.enName
    }));

    // 拼音首字母转换函数
    function getPinyinInitial(text) {
        const pinyinMap = {
            'a': '啊阿锕吖嗄腌錒',
            'b': '把八白百北本比边便变并步部',
            'c': '才参草层查差产长常场车成城吃出初处传春次从',
            'd': '大但当到道得的等地点电东动都度对多',
            'e': '而儿二',
            'f': '发法方分风服',
            'g': '该改干高告哥歌格个各给工公共古关观管光国果过',
            'h': '海好号合和河很红后候话回会',
            'j': '几己加见件建江交教叫接街金今进近经九就举句觉决军',
            'k': '开看考可课空口快',
            'l': '来老乐里力立利两亮量路论',
            'm': '马吗买卖满毛么没每门们面民名明命母目',
            'n': '那南难内能你年念鸟您牛农',
            'p': '怕排派跑朋片平',
            'q': '七期其奇起气千前钱强亲清情请秋球区取去全',
            'r': '然让热人认日容如入',
            's': '三色山商上少社身生师十时识实使世市事手书树双谁水说思斯死四送算虽随岁所',
            't': '他她它台太谈汤体天条听同头图',
            'w': '外完玩晚万王往网忘为位文问我无五午物',
            'x': '西息希习下先现线相想向象像小校笑些心新信星行形兴姓性学',
            'y': '样要药也业夜一医已以意因应影用由油游有又右鱼与语元员原远院月乐',
            'z': '在再早造怎站张找照者这真正知只中终钟种重周主住助注准着子字自走最作做坐座'
        };

        for (let [initial, chars] of Object.entries(pinyinMap)) {
            if (chars.includes(text[0])) {
                return initial;
            }
        }
        return text[0].toLowerCase();
    }

    // 渲染自定义语言选择面板
    document.addEventListener('DOMContentLoaded', function () {
        // 渲染语言面板
        const langGrid = document.getElementById('targetLangGrid');
        const searchInput = document.getElementById('langSearchInput');
        
        function renderLanguageButtons(languages) {
            langGrid.innerHTML = '';
            languages.forEach(lang => {
                const btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'lang-btn';
                btn.style.cssText = 'padding:8px 16px 8px 0;border:none;background:none;width:100%;text-align:center;font-size:1rem;cursor:pointer;border-radius:6px;transition:background 0.2s;';
                btn.textContent = lang.zhName;
                btn.dataset.code = lang.code;
                btn.onclick = function () {
                    document.getElementById('targetLang').value = lang.code;
                    document.getElementById('targetLangSelectedText').textContent = lang.zhName;
                    document.getElementById('targetLangPanel').style.display = 'none';
                };
                btn.onmouseover = function () { btn.style.background = '#f0f4ff'; };
                btn.onmouseout = function () { btn.style.background = 'none'; };
                langGrid.appendChild(btn);
            });
        }

        // 初始渲染所有语言
        renderLanguageButtons(languageList);

        // 搜索功能
        searchInput.addEventListener('input', function(e) {
            const searchText = e.target.value.toLowerCase();
            if (!searchText) {
                renderLanguageButtons(languageList);
                return;
            }

            const filteredLanguages = languageList.filter(lang => {
                const zhName = lang.zhName.toLowerCase();
                const enName = lang.enName.toLowerCase();
                const pinyinInitial = getPinyinInitial(lang.zhName);
                
                return zhName.includes(searchText) || 
                       enName.includes(searchText) || 
                       pinyinInitial === searchText[0];
            });

            renderLanguageButtons(filteredLanguages);
        });

        // 触发面板显示/隐藏
        const trigger = document.getElementById('targetLangPanelTrigger');
        const panel = document.getElementById('targetLangPanel');
        trigger.onclick = function (e) {
            panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
            if (panel.style.display === 'block') {
                searchInput.value = '';
                renderLanguageButtons(languageList);
            }
            e.stopPropagation();
        };
        // 点击外部关闭
        document.body.addEventListener('click', function () {
            panel.style.display = 'none';
        });
        panel.addEventListener('click', function (e) {
            e.stopPropagation();
        });
        // 默认选中第一个
        if (languageList.length > 0) {
            document.getElementById('targetLang').value = languageList[0].code;
            document.getElementById('targetLangSelectedText').textContent = languageList[0].zhName;
        }
        console.log("语言初始化完毕", languageList);
    });
</script>
<!-- Custom JS for translation page -->
<script>
    // 防抖函数
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 翻译函数
    async function translateText(sourceText) {
        if (!sourceText) {
            return;
        }

        // 获取我们的翻译语种
        const get_language = await axios({
            url: "/api/translate/baidu/black_widow/get_language/",
            method: 'GET',
            params: {
                "query": sourceText
            }
        });

        if (get_language.data.error == 0) {
            // 使用自动语言检测（修改to_lang为动态获取）
            axios({
                url: `/api/translate/baidu/black_widow/translate/?query=${sourceText}&from_lang=${get_language.data.lan}&to_lang=${document.getElementById('targetLang').value}`,
                method: 'GET',
            }).then(res => {
                console.log(res);
                const translatedText = res.data[0].dst;
                const detectedLang = get_language.data.lan || '未知语言';
                const translatedElement = document.getElementById('translatedText');
                const detectedLangElement = document.getElementById('detectedLang');

                // 更新检测到的语言显示
                detectedLangElement.textContent = `检测到: ${detectedLang}`;

                // 更新翻译结果
                translatedElement.textContent = translatedText;
                translatedElement.classList.remove('bw-placeholder');
                translatedElement.classList.add('bw-translated-text');
            }).catch(err => {
                console.log(err);
            }).finally(() => {
                console.log('翻译完成');
            });
        }
    }

    // 创建防抖的翻译函数
    const debouncedTranslate = debounce((text) => {
        translateText(text);
    }, 800); // 800ms 的防抖延迟

    // 字数统计和自动翻译
    const sourceText = document.getElementById('sourceText');
    const charCount = document.getElementById('charCount');
    sourceText.addEventListener('input', function () {
        const text = this.value.trim();
        charCount.textContent = text.length;
        
        // 触发防抖的翻译
        debouncedTranslate(text);
    });

    // 翻译按钮点击事件
    const translateBtn = document.querySelector("#translateBtn");
    translateBtn.addEventListener('click', () => {
        const text = sourceText.value.trim();
        translateText(text);
    });

    // 交流群徽章点击弹窗
    function setupGroupBadgeModal() {
        const groupBadge = document.querySelector('.group-badge');
        const groupModal = document.getElementById('groupModal');
        const closeGroupModal = document.getElementById('closeGroupModal');
        
        if (groupBadge && groupModal && closeGroupModal) {
            groupBadge.style.cursor = 'pointer';
            groupBadge.onclick = function () {
                groupModal.style.display = 'block';
                setTimeout(() => groupModal.classList.add('show'), 10);
            };
            closeGroupModal.onclick = function () {
                groupModal.classList.remove('show');
                setTimeout(() => groupModal.style.display = 'none', 180);
            };
            // 点击遮罩关闭
            groupModal.onclick = function (e) {
                if (e.target === groupModal) {
                    groupModal.classList.remove('show');
                    setTimeout(() => groupModal.style.display = 'none', 180);
                }
            };
        }
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function () {
        setupGroupBadgeModal();
    });

    // 其他按钮功能占位
    Array.from(document.querySelectorAll('.bw-card-header .bx')).forEach(function (icon) {
        icon.addEventListener('click', function () {
            console.log('点击了图标:', icon.className);
            if (icon.className.includes('bx-upload')) {
                // 上传文件
                const fileInput = document.createElement('input');
                fileInput.type = 'file';
                fileInput.accept = '.txt,.doc,.docx,.pdf'; // 支持的文件类型
                fileInput.onchange = function (e) {
                    const file = e.target.files[0];
                    if (file) {
                        // 检查文件类型
                        const allowedTypes = ['.txt', '.doc', '.docx', '.pdf'];
                        const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
                        if (!allowedTypes.includes(fileExtension)) {
                            showToast('请选择支持的文件格式（txt、doc、docx、pdf）', 'error');
                            return;
                        }

                        // 检查文件大小（限制为10MB）
                        const maxSize = 10 * 1024 * 1024; // 10MB
                        if (file.size > maxSize) {
                            showToast('文件大小不能超过10MB', 'error');
                            return;
                        }

                        // 创建FormData对象准备上传
                        const formData = new FormData();
                        formData.append('file', file);

                        showLoading("文件上传中...");
                        axios({
                            url: "{{BLACK_AI_DOMAIN}}api/ai/kimi/v1/upload_file/",
                            method: 'POST',
                            data: formData,
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        }).then(res => {
                            if (res.data.code == 0) {
                                // 成功
                                showToast(res.data.msg, 'success');
                                let fid = res.data.data.id;
                                showLoading("文件翻译中...");
                                axios({
                                    url: "/api/translate/ai/kimi/image_to_text/",
                                    method: 'GET',
                                    params: {
                                        fid: fid
                                    }
                                }).then(res => {
                                    // 更新翻译结果
                                    const translatedElement = document.getElementById('translatedText');
                                    translatedElement.textContent = res.data.data[0].dst;
                                    translatedElement.classList.remove('bw-placeholder');
                                    translatedElement.classList.add('bw-translated-text');
                                }).catch(err => {
                                    console.log(err);
                                    showToast('翻译失败', 'error');
                                }).finally(() => {
                                    hideLoading()
                                });
                            } else {
                                showToast(res.data.msg, 'error');
                                hideLoading()
                            }
                        }).catch(err => {
                            console.log(err);
                            showToast('上传失败', 'error');
                            hideLoading()
                        });
                    }
                };
                fileInput.click();
            } else if (icon.className.includes('bx-image')) {
                // 上传图片
                const fileInput = document.createElement('input');
                fileInput.type = 'file';
                fileInput.accept = 'image/*';
                fileInput.onchange = function (e) {
                    const file = e.target.files[0];
                    if (file) {
                        // 检查文件类型
                        if (!file.type.startsWith('image/')) {
                            showToast('请选择图片文件', 'error');
                            return;
                        }

                        // 检查文件大小（限制为5MB）
                        const maxSize = 5 * 1024 * 1024; // 5MB
                        if (file.size > maxSize) {
                            showToast('图片大小不能超过5MB', 'error');
                            return;
                        }

                        // 显示图片信息
                        const imageInfo = {
                            name: file.name,
                            size: (file.size / 1024 / 1024).toFixed(2) + 'MB',
                            type: file.type,
                            lastModified: new Date(file.lastModified).toLocaleString()
                        };


                        // 创建FormData对象准备上传
                        const formData = new FormData();
                        formData.append('image', file);

                        // 这里可以添加预览图片的代码
                        const reader = new FileReader();
                        reader.onload = function (e) {
                            // 可以在这里添加预览图片的UI显示
                        };
                        reader.readAsDataURL(file);
                        showLoading("图片上传中...");
                        axios({
                            url: "{{BLACK_AI_DOMAIN}}api/ai/kimi/v1/upload_image/",
                            method: 'POST',
                            data: formData,
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        }).then(res => {
                            if (res.data.code == 0) {
                                // 成功
                                showToast(res.data.msg, 'success');
                                let fid = res.data.data.id;
                                showLoading("图片转文本中...");
                                axios({
                                    url: "/api/translate/ai/kimi/image_to_text/",
                                    method: 'GET',
                                    params: {
                                        fid: fid
                                    }
                                }).then(res => {

                                    // 更新翻译结果
                                    const translatedElement = document.getElementById('translatedText');
                                    translatedElement.textContent = res.data.data[0].dst;
                                    translatedElement.classList.remove('bw-placeholder');
                                    translatedElement.classList.add('bw-translated-text');
                                }).catch(err => {
                                    console.log(err);
                                }).finally(() => {
                                    hideLoading()
                                });

                            } else {
                                showToast(res.data.msg, 'error');
                                hideLoading()
                            }
                        }).catch(err => {
                            console.log(err);
                        }).finally(() => {
                        });


                    }
                };
                fileInput.click();
            } else if (icon.className.includes('bx-copy')) {
                // 复制功能
                const translatedText = document.getElementById('translatedText');
                const textToCopy = translatedText.textContent;

                // 检查是否有可复制的内容
                if (!textToCopy || textToCopy === '翻译结果将显示在这里') {
                    showToast('没有可复制的内容', 'error');
                    return;
                }

                // 使用现代复制API
                navigator.clipboard.writeText(textToCopy).then(() => {
                    showToast('复制成功', 'success');
                    // 添加复制成功的视觉反馈
                    icon.style.color = '#377dff';
                    setTimeout(() => {
                        icon.style.color = '';
                    }, 1000);
                }).catch(err => {
                    console.error('复制失败:', err);
                    showToast('复制失败，请手动复制', 'error');
                });
            }
        });
    });

    console.log(document.querySelector('.group-badge'));
</script>
{% endblock %}

{% block nav_left %}{% include "pc/components/左侧导航栏.html" %}{% endblock %}
{% block NavBar %}{% endblock %}
{% include 'pc/公共样式配置/JS总样式.html' %}
{% block footer %}{% endblock %}